package com.qixia.sportsupload.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author Administrator
 * @Date 2023/12/7
 * @Description
 */
public class HttpClient {
    private static final HttpClientBuilder httpBuilder;
    private static final RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(30000).setConnectTimeout(30000).setConnectionRequestTimeout(30000).build();
    private static final Logger LOGGER = LoggerFactory.getLogger(HttpClient.class);

    public HttpClient() {
    }

    private static CloseableHttpClient getConnection() {
        return httpBuilder.build();
    }

    private static HttpUriRequest getRequestMethod(String content, String url, String method) {
        return getRequestMethod((Map)null, url, method, true, content);
    }

    private static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method, boolean useBody) {
        return getRequestMethod(map, url, method, useBody, "");
    }

    private static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method, boolean useBody, String bodyContent) {
        try {
            URL u = new URL(url);
            if ("https".equalsIgnoreCase(u.getProtocol())) {
                SslUtil.ignoreSsl();
            }
        } catch (Exception var10) {
            LOGGER.error("Itsoft httpClient ignore SSL met exception", var10);
        }

        HttpUriRequest reqMethod;
        Iterator var7;
        if (!useBody) {
            List<NameValuePair> params = new ArrayList();
            if (!CollectionUtils.isEmpty(map)) {
                var7 = map.keySet().iterator();

                while(var7.hasNext()) {
                    String s = (String)var7.next();
                    NameValuePair pair = new BasicNameValuePair(s, (String)map.get(s));
                    params.add(pair);
                }
            }

            if ("post".equals(method)) {
                reqMethod = RequestBuilder.post().setUri(url).addParameters((NameValuePair[])params.toArray(new NameValuePair[0])).setConfig(requestConfig).build();
            } else {
                reqMethod = RequestBuilder.get().setUri(url).addParameters((NameValuePair[])params.toArray(new NameValuePair[0])).setConfig(requestConfig).build();
            }
        } else {
            StringBuilder sb = new StringBuilder();
            if (StringUtils.isEmpty(bodyContent)) {
                var7 = map.entrySet().iterator();

                while(var7.hasNext()) {
                    Map.Entry<String, String> entry = (Map.Entry)var7.next();
                    sb.append((String)entry.getKey()).append("=").append((String)entry.getValue()).append("&");
                }
            } else {
                sb.append(bodyContent);
            }

            ByteArrayEntity entity = new ByteArrayEntity(sb.toString().getBytes(StandardCharsets.UTF_8));
            entity.setContentType("application/json");
            if ("post".equals(method)) {
                reqMethod = RequestBuilder.post().setUri(url).setEntity(entity).setConfig(requestConfig).build();
            } else {
                reqMethod = RequestBuilder.get().setUri(url).setEntity(entity).setConfig(requestConfig).build();
            }
        }

        reqMethod.addHeader("Accept-Charset", "utf-8");
        reqMethod.addHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.160 Safari/537.22");
        return reqMethod;
    }

    private static HttpUriRequest getRequestMethod(Map<String, String> map, String url, String method) {
        return getRequestMethod(map, url, method, false);
    }

    public static HttpResponse post(Map<String, String> map, String url) throws IOException {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post");
        return client.execute(post);
    }

    public static HttpResponse get(Map<String, String> map, String url) throws IOException {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "get");
        return client.execute(post);
    }

    public static JSONObject postJson(Map<String, String> map, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post");
        return executeRequest(client, post);
    }

    public static JSONObject postJson(Map<String, String> map, String url, Map<String, String> header) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post");
        if (!CollectionUtils.isEmpty(header)) {
            Iterator var5 = header.keySet().iterator();

            while(var5.hasNext()) {
                String s = (String)var5.next();
                post.setHeader(s, (String)header.get(s));
            }
        }

        return executeRequest(client, post);
    }

    public static JSONObject getJson(Map<String, String> map, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "get");
        return executeRequest(client, post);
    }

    public static String postStringBody(Map<String, String> map, String url, Map<String, String> header) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post", true);
        if (!CollectionUtils.isEmpty(header)) {
            Iterator var5 = header.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var5.next();
                post.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        return executeStringReq(client, post);
    }

    public static String postStringBody(Map<String, String> map, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post", true);
        return executeStringReq(client, post);
    }

    public static String postStringBody(String bodyContent, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(bodyContent, url, "post");
        return executeStringReq(client, post);
    }

    public static String postStringBody(String bodyContent, String url, Map<String, String> header) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(bodyContent, url, "post");
        if (!CollectionUtils.isEmpty(header)) {
            Iterator var5 = header.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var5.next();
                post.setHeader((String)entry.getKey(), (String)entry.getValue());
            }
        }

        return executeStringReq(client, post);
    }

    public static String getStringBody(String bodyContent, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest get = getRequestMethod(bodyContent, url, "get");
        return executeStringReq(client, get);
    }

    private static JSONObject executeRequest(CloseableHttpClient client, HttpUriRequest post) {
        CloseableHttpResponse response = null;

        JSONObject var5;
        try {
            response = client.execute(post);
            if (response.getStatusLine().getStatusCode() != 200) {
                post.abort();
                LOGGER.info("request fail,status={}", response.getStatusLine().getStatusCode());
                return null;
            }

            HttpEntity entity = response.getEntity();
            String message = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            var5 = JSON.parseObject(message);
        } catch (Exception var16) {
            LOGGER.error("request met exception", var16);
            return null;
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var15) {
                LOGGER.error("close http request fail", var15);
            }

        }

        return var5;
    }

    public static String postString(Map<String, String> map, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "post");
        return executeStringReq(client, post);
    }

    public static String getString(Map<String, String> map, String url) {
        CloseableHttpClient client = getConnection();
        HttpUriRequest post = getRequestMethod(map, url, "get");
        return executeStringReq(client, post);
    }

    private static String executeStringReq(CloseableHttpClient client, HttpUriRequest post) {
        CloseableHttpResponse response = null;

        String errorMsg;
        try {
            response = client.execute(post);
            HttpEntity entity;
            if (response.getStatusLine().getStatusCode() != 200 && response.getStatusLine().getStatusCode() != 201) {
                post.abort();
                entity = response.getEntity();
                errorMsg = EntityUtils.toString(entity, StandardCharsets.UTF_8);
                String headerMsg = Arrays.toString(response.getHeaders("authentication_exceptions"));
                LOGGER.error("request fail,status={},bodyMsg={},headerMsg={}", new Object[]{response.getStatusLine().getStatusCode(), errorMsg, headerMsg});
                String var6 = "";
                return var6;
            }

            entity = response.getEntity();
            errorMsg = EntityUtils.toString(entity, StandardCharsets.UTF_8);
        } catch (Exception var17) {
            LOGGER.error("request met exception", var17);
            return "";
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException var16) {
                LOGGER.error("close http request fail", var16);
            }

        }

        return errorMsg;
    }

    static {
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
        connectionManager.setMaxTotal(20);
        connectionManager.setDefaultMaxPerRoute(5);
        httpBuilder = HttpClients.custom();
        httpBuilder.setConnectionManager(connectionManager);
    }
}
